package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.dao.BspsDevBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsMchntBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsQrCodeInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsDevBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsQrCodeInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.DevBindInfo;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.entity.QrCodeInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.BindStatusEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.realize.PublicDealService;
import cc.rengu.igas.bsps.core.realize.impl.PublicDealServiceImpl;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.CashierOutRequest;
import cc.rengu.igas.bsps.facade.response.CashierOutResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/02
 * 1-法人解绑，用户表及绑定关系表逻辑删除，变更为失效状态（注册的用户）
 * 2-店长和收银员解绑，openId更新为空
 */
public class CashierOutService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        CashierOutRequest cashierOutRequest = new CashierOutRequest();
        ConvertUtil.convertOutput(cashierOutRequest);
        return cashierOutRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        CashierOutRequest cashierOutRequest = (CashierOutRequest) request;
        CashierOutResponse cashierOutResponse = new CashierOutResponse();
        /*获取请求信息：法人行号，用户标识，商户号，解绑商户号，收银员账号*/
        String instId = cashierOutRequest.getHeader().getInstId();
        String userId = cashierOutRequest.getUserId();
        String mchntNo = cashierOutRequest.getMchntNo();
        String unbindMchntNo = cashierOutRequest.getUnbindMchntNo();
        String cashierUserId = cashierOutRequest.getCashierId();
        rglog.info("法人行:" + instId + "用户标识:" + userId + "商户号:" + mchntNo + "解绑商户号:" + unbindMchntNo + "收银员用户标识ID:" + cashierUserId);
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(cashierUserId)) {
            rglog.error("必填性校验失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        /*根据商户号和登录账号查询用户信息*/
        BspsUserInfoMapper bspsUserInfoMapper = new BspsUserInfoMapperImpl();
        UserInfo userInfo = bspsUserInfoMapper.selectBspsUserInfoByUserId(instId, cashierUserId);
        if (null == userInfo) {
            rglog.error("查询收银员信息失败!法人行:<{}>，用户ID:<{}>", instId, cashierUserId);
            throw new BizException(RespCodeEnum.QUERY_NULL.getRespCode(), RespCodeEnum.QUERY_NULL.getRespDesc());
        }
        /*判断用户是否有权限进行收银员的解绑操作*/
        PublicDealService publicDealService = new PublicDealServiceImpl();
        boolean authFlag = publicDealService.checkUserOpAuth(instId, mchntNo, userId, cashierUserId);
        if (!authFlag) {
            rglog.error("用户无权限解绑该收银员");
            throw new BizException(RespCodeEnum.USER_NO_AUTHORITY.getRespCode(), RespCodeEnum.USER_NO_AUTHORITY.getRespDesc());
        }

        int iReturnCode;
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        //用户不存在pc端用户名
        if ("LOGINID".equals(userInfo.getUserLoginId())) {
            /*解绑收银员操作:1-收银员信息解绑 2-收银员绑定的二维码解绑  3-收银员绑定的设备解绑*/

            /*0-用户表信息更新-用户表更新为解绑状态 */
            BspsMchntBindInfoMapper bspsMchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
            List<MchntBindInfo> mchntBindInfoList = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserId(instId, userId);
            if (!CollectionUtils.isEmpty(mchntBindInfoList) && mchntBindInfoList.size() == 1) {
                userInfo.setUserStatus("01");
                userInfo.setLastOprId(userId);
                userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                iReturnCode = bspsUserInfoMapper.updateBspsUserInfoByPrimaryKey(userInfo);
                if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("收银员解绑失败,iReturnCode:<{}>", iReturnCode);
                    throw new BizException(RespCodeEnum.CASHIER_UNBIND_ERROR.getRespCode(), RespCodeEnum.CASHIER_UNBIND_ERROR.getRespDesc());
                }
            }
            /*1-收银员信息解绑--根法人行号+绑定用户ID+绑定商户号 筛选二维码进行更新操作*/
            /*更新信息赋值*/
            MchntBindInfo mchntBindInfo = new MchntBindInfo();
            /*更新为解绑状态*/
            mchntBindInfo.setBindStatus(BindStatusEnum.UNBIND.getStatus());
            /*二维码绑定人id*/
            mchntBindInfo.setBindUserId(userInfo.getUserId());
            /*二维码绑定商户*/
            mchntBindInfo.setMchntNo(mchntNo);
            /*法人行信息*/
            mchntBindInfo.setInstId(instId);
            /*最后操作信息*/
            mchntBindInfo.setLastOprId(userId);
            mchntBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            mchntBindInfo.setUnBindDate(DateUtil.getCurrentDate());
            mchntBindInfo.setUnBindTime(DateUtil.getCurrentTime());
            iReturnCode = bspsMchntBindInfoMapper.updateBspsMchntBindInfoStatusByUserIdAndMchntNo(instId, mchntBindInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("收银员解绑失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.CASHIER_UNBIND_ERROR.getRespCode(), RespCodeEnum.CASHIER_UNBIND_ERROR.getRespDesc());
            }
            /*3-设备解绑（手机和语音设备）*/
            BspsDevBindInfoMapper bspsDevBindInfoMapper = new BspsDevBindInfoMapperImpl();
            DevBindInfo devBindInfo = new DevBindInfo();
            /*根法人行号+商户号+绑定人员id筛选数据*/
            devBindInfo.setInstId(instId);
            devBindInfo.setBindMchntNo(mchntNo);
            devBindInfo.setBindUserId(userInfo.getUserId());
            devBindInfo.setBindStatus(BindStatusEnum.UNBIND.getStatus());
            /*最后操作信息*/
            devBindInfo.setLastOprId(userId);
            devBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            devBindInfo.setUnBindDate(DateUtil.getCurrentDate());
            devBindInfo.setUnBindTime(DateUtil.getCurrentTime());
            iReturnCode = bspsDevBindInfoMapper.updateBspsDevBindInfoStatusByUserIdAndMchntNo(instId, devBindInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("解绑收银员设备失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.UNBIND_DEVBINDINFO_ERROR.getRespCode(), RespCodeEnum.UNBIND_DEVBINDINFO_ERROR.getRespDesc());
            }
            dbsUtil.dbsEndTransaction(true);

            /*2-二维码信息解绑*/
            BspsQrCodeInfoMapper bspsQrCodeInfoMapper = new BspsQrCodeInfoMapperImpl();
            QrCodeInfo qrCodeInfo = new QrCodeInfo();
            /*根据法人行号，商户号，绑定人筛选解绑二维码数据*/
            qrCodeInfo.setInstId(instId);
            qrCodeInfo.setMchntNo(mchntNo);
            qrCodeInfo.setLogoUrlPath("");
            qrCodeInfo.setRemark3("");
            qrCodeInfo.setUserId(userInfo.getUserId());
            qrCodeInfo.setBindStatus("00");
            /*最后操作信息*/
            qrCodeInfo.setLastOprId(userId);
            qrCodeInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            iReturnCode = bspsQrCodeInfoMapper.updateBspsQrCodeInfoStatusByUserIdAndMchntNo(qrCodeInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                rglog.error("二维码解绑失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespDesc());
            }

        } else {
            //pc端用户账户存在，只更新openId为默认值
            iReturnCode = bspsUserInfoMapper.updateBspsOpenIdByPrimaryKey(userInfo, "OPENID");
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("收银员解绑失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.CASHIER_UNBIND_ERROR.getRespCode(), RespCodeEnum.CASHIER_UNBIND_ERROR.getRespDesc());
            }
            dbsUtil.dbsEndTransaction(true);
        }
        /* 拼装响应结果 */
        BizResponse<CashierOutResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(cashierOutResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        CashierOutResponse cashierOutResponse = (CashierOutResponse) bizResponse.getResult();
        ConvertUtil.convertInput(cashierOutResponse);
    }
}
